﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using 算法入门.Domain.Operations;

namespace 算法入门.Utils
{
    public static class PermissionHelper
    {
        /// <summary>
        /// 遍历枚举类型Permission中的所有值，得到枚举的整形值和它的Description描述还有二进制字符串
        /// </summary>
        /// <returns></returns>
        public static List<PermissionItem> GetAllPermissions()
        {
            return Enum.GetValues(typeof(Permission))
                .Cast<Permission>()
                .Select(p => new PermissionItem
                {
                    PerVal = (int)p,
                    PerName = GetEnumDescription(p),
                    PerBinStr = BitOperatorHelp.GetBitStr((int)p)
                }).ToList();
        }

        private static string GetEnumDescription(Enum value)
        {
            FieldInfo field = value.GetType().GetField(value.ToString());
            DescriptionAttribute attribute = field.GetCustomAttribute<DescriptionAttribute>();
            return attribute?.Description ?? value.ToString();
        }

        /// <summary>
        /// 判断用户是否具有指定的枚举权限
        /// </summary>
        /// <param name="userPermissions"></param>
        /// <param name="permission"></param>
        /// <returns></returns>
        public static bool HasPermission(int userPermissions,Permission permission)
        {
            return (userPermissions & (int)permission) == (int)permission;
        }

        /// <summary>
        /// 添加指定权限后并返回
        /// </summary>
        /// <param name="userPermissions"></param>
        /// <param name="permission"></param>
        /// <returns></returns>
        public static int AddPermission(int userPermissions,Permission permission)
        {
            return userPermissions | (int)permission;
        }

        /// <summary>
        /// 删除指定权限并返回
        /// </summary>
        /// <param name="userPermissions"></param>
        /// <param name="permission"></param>
        /// <returns></returns>
        public static int DelPermission(int userPermissions,Permission permission)
        {
            return userPermissions & ~(int)permission;
        }
    }
}
